package com.ruoyi.web.controller.business.goods;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.goods.domain.JbCommodity;
import com.ruoyi.business.goods.domain.JbCommodityOfflinePrice;
import com.ruoyi.business.goods.domain.JbProductClassify;
import com.ruoyi.business.goods.service.JbCommodityService;
import com.ruoyi.business.goods.service.JbProductService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.controller.business.goods.factory.JbCommodityFactory;
import com.ruoyi.web.controller.business.goods.factory.JbCommodityOfflinePriceFactory;
import com.ruoyi.web.controller.business.goods.factory.JbProductClassifyFactory;
import com.ruoyi.web.core.JoR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 商品 Controller
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Api("商品")
@RestController
@RequestMapping("/commodity")
public class JbCommodityController extends BaseController
{
    @Autowired
    private JbCommodityService service;
    @Autowired
    private JbProductService jbProductService;
    @Autowired
    private JbCommodityFactory factory;
    @Autowired
    private JbProductClassifyFactory jbProductClassifyFactory;
    @Autowired
    private JbCommodityOfflinePriceFactory jbCommodityOfflinePriceFactory;
    @Autowired
    private JbCommodityFactory jbCommodityFactory;

    /**
     * 查询商品列表
     */
    @ApiOperation("查询商品列表")
    // @PreAuthorize("@ss.hasPermi('commodity:list')")
    @GetMapping("/list")
    public TableDataInfo list(PageParam page, JbCommodity jbCommodity)
    {
        return JoR.rows(factory.list(page, jbCommodity));
    }

    /**
     * 导出商品列表
     */
    @ApiOperation("导出商品列表")
    @PreAuthorize("@ss.hasPermi('commodity:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PageParam page, JbCommodity jbCommodity)
    {
        LambdaQueryWrapper<JbCommodity> select = new LambdaQueryWrapper<>();
        IPage<JbCommodity> iPage = service.page(page.b(), select);

        List<JbCommodity> list = iPage.getRecords();
        ExcelUtil<JbCommodity> util = new ExcelUtil<JbCommodity>(JbCommodity.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @ApiOperation("获取商品详细信息")
    @PreAuthorize("@ss.hasPermi('commodity:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id, String deptId)
    {
        return success(factory.getInfo(id, deptId));
    }

    @ApiOperation("获取商品详细信息组")
    @PreAuthorize("@ss.hasPermi('commodity:query')")
    @GetMapping(value = "/listByIds/{ids}")
    public AjaxResult listByIds(@PathVariable("ids") Long[] ids, String deptId)
    {
        List<JbCommodity> jbCommodities = new ArrayList<>();
        for (Long id : ids)
        {
            jbCommodities.add(factory.getInfo(id, deptId));
        }
        return success(jbCommodities);
    }

    /**
     * 新增商品
     */
    @ApiOperation("新增商品")
    @PreAuthorize("@ss.hasPermi('commodity:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody JbCommodity jbCommodity)
    {
        return JoR.success(factory.add(jbCommodity));
    }

    /**
     * 修改商品
     */
    @ApiOperation("修改商品")
    @PreAuthorize("@ss.hasPermi('commodity:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody JbCommodity jbCommodity) throws InvocationTargetException,
            NoSuchMethodException, IllegalAccessException
    {
        return AjaxResult.success(factory.edit(jbCommodity));
    }

    /**
     * 修改状态
     */
    @ApiOperation("修改状态")
    @PreAuthorize("@ss.hasPermi('product:isStatus')")
    @Log(title = "修改状态", businessType = BusinessType.UPDATE)
    @PutMapping("/isStatus")
    public AjaxResult isStatus(@RequestBody JbCommodity entity)
    {
        LambdaUpdateWrapper<JbCommodity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(JbCommodity::getId, entity.getId());
        updateWrapper.set(JbCommodity::getStatus, entity.getStatus());

        return toAjax(service.update(updateWrapper));
    }

    /**
     * 删除商品
     */
    @ApiOperation("删除商品")
    @PreAuthorize("@ss.hasPermi('commodity:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(service.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 新增产品分类
     */
    @ApiOperation("新增产品分类")
    @PreAuthorize("@ss.hasPermi('commodity:classify:add')")
    @Log(title = "新增产品分类", businessType = BusinessType.INSERT)
    @PostMapping("/addClassify")
    public AjaxResult addCommodity(@RequestBody JbProductClassify jbProductClassify)
    {
        jbProductClassify.setType(JbProductClassifyFactory.COMMODIYTYPE);
        return jbProductClassifyFactory.addOrEdit(jbProductClassify);
    }

    /**
     * 删除产品分类
     */
    @ApiOperation("删除产品分类")
    @PreAuthorize("@ss.hasPermi('commodity:classify:remove')")
    @Log(title = "删除产品分类", businessType = BusinessType.INSERT)
    @DeleteMapping("/removeClassify/{ids}")
    public AjaxResult removeClassify(@PathVariable Long[] ids)
    {
        return jbProductClassifyFactory.remove(ids);
    }

    /**
     * 查询产品分类树
     */
    @ApiOperation("查询产品分类树")
    // @PreAuthorize("@ss.hasPermi('commodity:classify:add')")
    @Log(title = "查询产品分类树", businessType = BusinessType.INSERT)
    @GetMapping("/listClassify")
    public AjaxResult listClassify()
    {
        return AjaxResult.success(factory.listClassify());
    }

    /**
     * 查询商品名称和产品农药列表
     */
    @ApiOperation("查询商品名称和产品农药列表")
    @PreAuthorize("@ss.hasPermi('commodity:listNameAll')")
    @GetMapping("/listNameAll")
    public AjaxResult listNameAll(PageParam page, JbCommodity jbCommodity)
    {
        return success(factory.listNameAll(jbCommodity));
    }

    /**
     * 查询商品列表，根据登录人部门渠道类型
     */
    @ApiOperation("查询商品列表，根据登录人部门渠道类型")
    @GetMapping("/listType")
    public TableDataInfo listType(PageParam page, JbCommodity jbCommodity)
    {
        return JoR.rows(factory.listType(page, jbCommodity));
    }

    /**
     * 查询商品列表，根据登录人部门渠道类型
     */
    @ApiOperation("查询商品列表，根据登录人部门渠道类型")
    @GetMapping("/channelType")
    public AjaxResult listType(Long[] ids, String priceType)
    {
        if (getLoginUser().getUser().getDept().getChannel().equals("1001"))
        {
            List<JbCommodity> list = service.list(new LambdaQueryWrapper<JbCommodity>()
                    .in(JbCommodity::getId, ids));

            JSONArray jsonArray = new JSONArray();
            for (JbCommodity jbCommodity : list)
            {
                switch (priceType)
                {
                    case "1001" -> jsonArray.add(new JSONObject().fluentPut(jbCommodity.getId() + "",
                            jbCommodity.getOnlineUnitPrice()));
                    case "1002" -> jsonArray.add(new JSONObject().fluentPut(jbCommodity.getId() + "",
                            jbCommodity.getCaseUnitPrice()));
                    case "1003" -> jsonArray.add(new JSONObject().fluentPut(jbCommodity.getId() + "",
                            jbCommodity.getTonPrice()));
                }
            }
            return JoR.success(jsonArray);
        } else
        {
            JSONArray jsonArray = new JSONArray();
            for (Long id : ids)
            {
                List<JbCommodityOfflinePrice> list = jbCommodityOfflinePriceFactory.list(id,
                        getLoginUser().getDeptId() + "");
                JbCommodityOfflinePrice jbCommodityOfflinePrice = list.get(0);
                switch (priceType)
                {
                    case "1001" ->
                            jsonArray.add(new JSONObject().fluentPut(jbCommodityOfflinePrice.getCommodityId() + "",
                                    jbCommodityOfflinePrice.getFactoryPrice()));
                    case "1002" ->
                            jsonArray.add(new JSONObject().fluentPut(jbCommodityOfflinePrice.getCommodityId() + "",
                                    jbCommodityOfflinePrice.getCustomPrice()));
                    case "1003" ->
                            jsonArray.add(new JSONObject().fluentPut(jbCommodityOfflinePrice.getCommodityId() + "",
                                    jbCommodityOfflinePrice.getTonPrice()));
                }
            }
            return JoR.success(jsonArray);
        }
    }

    /**
     * 查询商品折算价格，根据登录人部门
     */
    @ApiOperation("查询商品折算价格，根据登录人部门")
    @GetMapping("/conversion")
    public AjaxResult conversion(Long[] ids)
    {
        return JoR.success(jbCommodityFactory.conversion(ids));
    }

    /**
     * 查询商品列表，根据登录人部门渠道类型
     */
    @ApiOperation("查询商品列表，根据登录人部门渠道类型")
    @GetMapping("/initializationConversion")
    public AjaxResult initializationConversion()
    {
        for (JbCommodity jbCommodity : service.list())
        {
            jbCommodity.setOfflinePrices(jbCommodityOfflinePriceFactory.list(jbCommodity.getId()));
            factory.edit(jbCommodity);
        }
        return JoR.success();
    }

}
